<script setup>
    import {ref, onMounted} from 'vue'
    import useUserInfoStore from '@/stores/userInfo.js'
    import {useTokenStore} from '@/stores/token.js'
    import { ElMessage, ElMessageBox } from 'element-plus';
    import {useRouter} from 'vue-router'
    import {workOrderPageQueryService, workOrderGetService, workOrderDeleteService, workOrderAddService} from '@/api/workOrder.js'
    import {getWorkOrderTypeName, getWorkOrderStatusName, workOrderTypeList, workOrderStatusList} from '@/utils/workOrder.js'
    import { getDistrictTree, parseDistrictTree } from '@/utils/district.js';
    import WorkOrderVerify from './WorkOrderVerify.vue'
    import { getDateTimeString } from '@/utils/date.js';


    const uploadRef = ref()
    const userInfoStore = useUserInfoStore();
    const tokenStore = useTokenStore();
    const router = useRouter();

    const parsedDistrictTreeData = ref([])

    //列表的物品总数
    const itemsTotal = ref(1);

    //片区分页查询的表单结构
    const workOrderPageQueryData = ref({
        page: 1,
        pageSize: 5,
        id: null,
        deviceId: null,
        districtId: null,      
        type: null,      
        status: null,      
        warId: null,
        sepId: null,
        repId: null,
        jugId: null,
    })

    const workOrder = ref([])

    //定义表单校验规则
    const rules = {
        deviceId: [
            { required: true, message: '设备ID不能为空', trigger: 'blur' },
        ],
    }

    //分页查询获取用户列表
    const getworkOrderList = async()=>{
        console.log('get')
        let result = await workOrderPageQueryService(workOrderPageQueryData.value);
        workOrder.value = result.records
        itemsTotal.value = result.total
        console.log(result.records)
        for(let i = 0;i < workOrder.value.length; i++){
            workOrder.value[i].typeName = getWorkOrderTypeName(workOrder.value[i])
            workOrder.value[i].statusName = getWorkOrderStatusName(workOrder.value[i])
        }
    }

    //分页查询获取用户列表
    const getWorkOrder = async(id)=>{
        console.log('get')
        let result = await workOrderGetService(id);
        let workOrderItem = result.data
        workOrderItem.typeName = getWorkOrderTypeName(workOrderItem)
        workOrderItem.statusName = getWorkOrderStatusName(workOrderItem)
        workOrderItem.timeSend = workOrderItem.timeSend ? getDateTimeString(workOrderItem.timeSend) : '/'
        workOrderItem.timeAccept = workOrderItem.timeAccept ? getDateTimeString(workOrderItem.timeAccept) : '/'
        workOrderItem.timeProcess = workOrderItem.timeProcess ? getDateTimeString(workOrderItem.timeProcess) : '/'
        workOrderItem.timeCompleted = workOrderItem.timeCompleted ? getDateTimeString(workOrderItem.timeCompleted) : '/'
        return workOrderItem
    }

    //页面加载时获取一次工单
    onMounted( async ()=>{
        parsedDistrictTreeData.value = await getDistrictTree()
        //console.log(parsedDistrictTreeData.value)
        getworkOrderList()
    })
    
    //分页大小改变时重新分页查询
    const handleSizeChange = (val) => {
        workOrderPageQueryData.value.pageSize = val
        getworkOrderList()
    }
    //分页页码改变时重新分页查询
    const handleCurrentChange = (val) => {
        workOrderPageQueryData.value.page = val
        getworkOrderList()
    }

    //是否在编辑，若为true则呼出右侧编辑窗口
    const isEditing = ref(false)
    //当前片区，用于承载编辑用户与添加用户的表单
    const currentWorkOrder = ref({})

    const isVerifying = ref(false)

    const verifyWorkOrder = async (row) =>{
        currentWorkOrder.value = await getWorkOrder(row.id);
        isVerifying.value = true   
    }

    
    const verifyComplete = async (row) =>{
        await getworkOrderList()
        isVerifying.value = false   
    }

    //删除用户使用ElMessageBox判断
    const deleteWorkOrder = (row) =>{
        ElMessageBox.confirm(
            '要删除该工单吗?',
            'Warning',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then( async () => {
                let id = row.id;
                let result = await workOrderDeleteService(id)
                ElMessage.success(result.data? result.data : '删除成功');
                getworkOrderList()
        }).catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })

    }

    //是否在添加新用户，若为true则呼出右侧新增用户窗口
    const isAdding = ref(false)

    const addWorkOrder = async() => {
         //调用接口
        let result = await workOrderAddService(currentWorkOrder.value);
        ElMessage.success(result.data? result.data : '新增成功');
    }

    
    //添加新用户，初始化currentWorkOrder表单
    const addWorkOrderButton = () =>{
        currentWorkOrder.value = {
            id: 0,
            deviceId: '',
            warId: '',
            type: '',
            commentOrder: '',
            status: null,
            repairRecords: null,
        }
        isAdding.value = true;
    }

    //取消新增用户
    const cancelClickAdding = () =>{
        isAdding.value = false
    }

    //提交新增用户
    const confirmClickAdding = async () =>{
        await addWorkOrder()
        isAdding.value = false
        getworkOrderList()
    }


</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>工单管理</span>
            </div>
        </template>

        <div>
            <!-- 顶部栏，包含分页查询过滤条件，以及创建新用户 -->
            <el-form class="search-filter" :model="workOrderPageQueryData">
                <el-form-item label="ID">
                    <el-input v-model="workOrderPageQueryData.id" type="number" clearable></el-input>
                </el-form-item>
                <el-form-item label="类型">
                    <el-select
                        v-model="workOrderPageQueryData.type"
                        placeholder="选择工单类型"
                        clearable
                        size="large"
                        >
                            <el-option
                            v-for="item in workOrderTypeList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            />
                        </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select
                        v-model="workOrderPageQueryData.status"
                        placeholder="选择工单状态"
                        clearable
                        size="large"
                        >
                            <el-option
                            v-for="item in workOrderStatusList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            />
                        </el-select>
                </el-form-item>
                <el-form-item label="所属片区">
                    <el-tree-select
                        v-model="workOrderPageQueryData.districtId"
                        :data="parsedDistrictTreeData"
                        check-strictly
                        clearable
                        :render-after-expand="false"
                        style="width: 240px"
                    />
                </el-form-item>
                <el-form-item>
                        <el-button type="primary" @click="getworkOrderList">搜索</el-button>
                </el-form-item>
                <el-form-item>
                        <el-button @click="addWorkOrderButton">新增手动工单</el-button>
                </el-form-item>
            </el-form>
        </div>

        <hr style="background-color: #eee; height: 1px; border: none;"/>

        <!-- 用户表格 -->
        <el-table :data="workOrder" style="width: 100%">
            <el-table-column prop="id" label="ID" width="180" sortable  />
            <el-table-column prop="deviceId" label="设备ID" width="180" sortable  />
            <el-table-column prop="deviceName" label="设备名称" width="180" sortable  />
            <el-table-column prop="districtName" label="片区名称" sortable />
            <el-table-column prop="typeName" label="类型" sortable />
            <el-table-column prop="statusName" label="状态" sortable />
            <el-table-column prop="operations" label="操作" fixed="right">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="verifyWorkOrder(scope.row)">{{ scope.row.status === 'processing' ? '审核' : '查看' }}</el-button>
                    <el-button link type="danger" size="small" @click="deleteWorkOrder(scope.row)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <!-- 页码切换组件 -->
        <div class="pagination-block">
            <el-pagination layout="prev, pager, next, sizes" :total="itemsTotal" :page-size="workOrderPageQueryData.pageSize"
            v-model:current-page="workOrderPageQueryData.page"
            v-model:page-size="workOrderPageQueryData.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
    </el-card>

        <!-- 查看设备详情的弹窗 -->
    <el-dialog v-model="isVerifying" title="审核工单" width="80%" fullscreen destroy-on-close center>
        <WorkOrderVerify :workOrderData="currentWorkOrder" @close="verifyComplete" />
    </el-dialog>

  <!-- 新增手动工单的侧边界面 -->
  <el-drawer v-model="isAdding" :direction="rtl" size="50%">
        <template #header>
            <h4>新增手动工单</h4>
        </template>
        <template #default>
            <div class="form-edit-user" >
                <el-row>
                    <el-col :span="18">
                        <el-form :model="currentWorkOrder" :rules="rules" label-width="150px" size="large">
                            <el-form-item label="设备ID" prop="deviceId">
                                <el-input v-model="currentWorkOrder.deviceId" type="number"></el-input>
                            </el-form-item>
                            <el-form-item label="描述" prop="commentOrder">
                                <el-input v-model="currentWorkOrder.commentOrder" type="textarea"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
        <div style="flex: auto">
            <el-button @click="cancelClickAdding">取消</el-button>
            <el-button type="primary" @click="confirmClickAdding">确认</el-button>
        </div>
        </template>
  </el-drawer>

</template>

<style scoped>
    .search-filter {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }

    .pagination-block{
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .form-edit-user {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .form-edit-user-avatar {
        display: flex;
        justify-content: center;
        padding: 32px;
    }
    
</style>
